from mxupy import IM, EntityXControl
import OBEvolutionAI as obe
import bigOAINet as bigo
import hashlib



class StudentControl(EntityXControl):
    class Meta:
        model_class = obe.Student

    def register(self, username, realname, password, num, email, phone, schoolId, collegeId, majorId, deptId):

        """
        学生注册方法
        """
        
        # 学校等毋须校验
        # if (im := obe.SchoolControl.inst().exists_by_id(schoolId)).error:
        #     return im
        # if not im.data:
        #     return im.set_error("学校不存在")

            
            # # 验证外键关联数据是否存在
            # try:


            #     school = bigo.School.get(bigo.School.schoolId == schoolId)
            #     college = bigo.College.get(bigo.College.collegeId == collegeId)
            #     major = bigo.Major.get(bigo.Major.majorId == majorId)
            #     # dept可以为0或有效ID
            #     if deptId and deptId != 0:
            #         dept = bigo.Dept.get(bigo.Dept.deptId == deptId)
            #     logger.info("关联数据验证通过")
            # except DoesNotExist as e:
            #     error_msg = f"关联数据不存在，请检查学校/学院/专业信息"
            #     logger.error(error_msg, exc_info=True)
            #     return IM(False, error_msg, {
            #         "error_type": "invalid_data",
            #         "error_detail": str(e)
            #     })
        # 对密码进行SHA256加密
        hashed_password = hashlib.sha256(password.encode('utf-8')).hexdigest()

        # 创建用户    
        if (im := bigo.UserControl.inst().add(
            {   
                "username": username,
                "nickname": username,
                "realname": realname,
                "password": hashed_password,
                "email": email,
                "phone": phone,
                "role": "student",
                "num": num,
                "isActive": 1
            }
        )).error:
            return im
        userId = im.data.userId
        # 创建学生记录

        if (im := obe.StudentControl.inst().add(
            {   
                "collegeId": collegeId,
                "userId": userId,
                "stuNum": num,
                "schoolId": schoolId,
                "collegeId": collegeId,
                "majorId": majorId,
                "deptId": deptId 
            }
        )).error:
            return im
        return im
        
        #     userId = im.data["userId"]


        #     student = self.meta.model_class.create(
                    
        #         )


            
        #     # # 创建用户账户
        #     # try:





        #     #     user = bigo.User.create(
        #     #         username=username,
        #     #         password=password,
        #     #         email=email,
        #     #         phone=phone,
        #     #         role="student",
        #     #         num=num,
        #     #         nickName=username
        #     #     )
        #     # except IntegrityError as e:
        #     #     logger.error(f"用户名或学号已存在: {str(e)}", exc_info=True)
        #     #     return IM(False, "用户名或学号已存在", {
        #     #         "error_type": "user_exists",
        #     #         "error_detail": str(e)
        #     #     })
        #     # except Exception as e:
        #     #     logger.error(f"创建用户账户失败: {str(e)}", exc_info=True)
        #     #     return IM(False, f"创建用户账户失败: {str(e)}", {
        #     #         "error_type": "user_creation_failed",
        #     #         "error_detail": str(e)
        #     #     })
            
        #     # 创建学生记录
        #     try:
                
        #     except IntegrityError as e:
        #         # 如果学生记录创建失败，删除已创建的用户
        #         user.delete_instance()
        #         logger.error(f"学号已存在: {str(e)}", exc_info=True)
        #         return IM(False, "学号已存在", {
        #             "error_type": "stu_num_exists",
        #             "error_detail": str(e)
        #         })
        #     except Exception as e:
        #         # 如果学生记录创建失败，删除已创建的用户
        #         user.delete_instance()
        #         logger.error(f"创建学生记录失败: {str(e)}", exc_info=True)
        #         return IM(False, f"创建学生记录失败: {str(e)}", {
        #             "error_type": "student_creation_failed",
        #             "error_detail": str(e)
        #         })
            
        #     # 准备返回数据
        #     result_data = {
        #         "userId": user.userId,
        #         "username": user.username,
        #         "stuNum": student.stuNum,
        #         "schoolId": student.school_id,
        #         "collegeId": student.college_id,
        #         "majorId": student.major_id,
        #         "deptId": student.dept_id
        #     }
            
        #     logger.info(f"学生注册成功: userId={user.userId}, username={user.username}")
        #     return IM(True, "注册成功", result_data)
            
        # except Exception as e:
        #     logger.error(f"注册过程中出现未预期的错误: {str(e)}", exc_info=True)
        #     return IM(False, "注册过程中出现错误", {
        #         "error_type": "unexpected_error",
        #         "error_detail": str(e)
        #     })